package com.demo.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZKNodeExist implements Watcher {

    private ZooKeeper zooKeeper = null;

    public static final String zkServerPath = "127.0.0.1:12181";
    public static final Integer timeout = 5000;
    private static Stat stat = new Stat();

    public ZKNodeExist() {}

    public ZKNodeExist(String connectString) {
        try {
            zooKeeper = new ZooKeeper(connectString, timeout, new ZKNodeExist());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws KeeperException, InterruptedException {
        ZKNodeExist zkServer = new ZKNodeExist(zkServerPath);

        Stat stat = zkServer.getZooKeeper().exists("/imooc-fake", true);
        if (stat != null) {
            System.out.println("查询的节点版本为dataVersion: " + stat.getVersion());
        } else {
            System.out.println("该节点不存在...");
        }
        countDownLatch.await();
    }

    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }

    public void setZooKeeper(ZooKeeper zooKeeper) {
        this.zooKeeper = zooKeeper;
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            System.out.println("节点数据改变");
            countDownLatch.countDown();
        } else if (watchedEvent.getType() == Event.EventType.NodeCreated) {
            System.out.println("节点创建");
            countDownLatch.countDown();
        } else if (watchedEvent.getType() == Event.EventType.NodeDeleted) {
            System.out.println("节点删除");
            countDownLatch.countDown();
        }
    }
}
